<?php
namespace app\components;

use yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use app\models\Fans;

class BaseController extends Controller
{
    // 回调域名
    const WWW_ADDRESS = 'http://bd536971.ngrok.io';

    // 微信回调获取用户信息state常量
    const WECHAT_USERINFO_STATE = 'bmob_renmai';

    // 用户session名前缀
    // const SESSION_USERINFO = 'session_user';

    // 用户数据
    private $user;

    // 视图
    public $layout = '@callmez/wechat/views/web/layouts/main';

    // 获取当前登录用户信息
    public function getCurrentUser($refresh = true)
    {
        if($refresh){
        	$userinfo = $this->getUserFromWechat();
        	if(!empty($userinfo)){
        	    // 从数据库中读取是否存在该用户uid
        	    $user = $this->getUIDByOpenid($userinfo['openid']);
        	    if(!empty($user)){
        	        $userinfo['uid'] = $user->uid;
        	    }
        	}

        	// 写入session
        	Yii::$app->session->set('userinfo', $userinfo);
        }
        
        // 读session 
        return Yii::$app->session->get('userinfo');
    }

    // 更新登录用户信息
    public function setCurrentUser($data)
    {
        return Yii::$app->session->set('userinfo', $data);
    }

    // 微信回调获取用户信息
    private function getUserFromWechat()
    {
        $wechat = Yii::$app->wechat;
        if(isset($_GET['state']) && $_GET['state'] == self::WECHAT_USERINFO_STATE){
            $code = $_GET['code'];

            // 根据code获取网页版的access_token，openid等信息
            $authinfo = $wechat->getOauth2AccessToken($code);
            $openid = $authinfo['openid'];
            $access_token = $authinfo['access_token'];

            // 通过openid获取用户信息
            $userinfo = $wechat->getSnsMemberInfo($openid, $access_token);
	
	return $userinfo;            
        }else{
            // 获取code
            $ret1 = $wechat->getOauth2AuthorizeUrl(self::getCurrentURL(), self::WECHAT_USERINFO_STATE, 'snsapi_userinfo');
            header("Location: {$ret1}");
        }
    }

    // 获取jsapi配置
    protected function getJsAPIConfig()
    {
        return Yii::$app->wechat->jsApiConfig();
    }

    // 下载微信服务器文件
    protected function getMedia($media_id)
    {
        return Yii::$app->wechat->getMedia($media_id);
    }

    // 获取当前url
    public static function getCurrentURL()
    {
        return 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    }

    // openid -> uid 数据库
    protected function getUIDByOpenid($openid)
    {
        return Fans::find()->where(['openid' => $openid])->one();
    }
}